package com.app.oral.config

import com.app.oral.model.ExerciseStage
import org.apache.ibatis.type.BaseTypeHandler
import org.apache.ibatis.type.JdbcType
import org.apache.ibatis.type.MappedTypes
import java.sql.CallableStatement
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.sql.SQLException

/**
 * 练习阶段自定义TypeHandler
 * 处理数据库字符串与ExerciseStage枚举之间的映射
 */
@MappedTypes(ExerciseStage::class)
class ExerciseStageTypeHandler : BaseTypeHandler<ExerciseStage>() {

    @Throws(SQLException::class)
    override fun setNonNullParameter(ps: PreparedStatement, i: Int, parameter: ExerciseStage, jdbcType: JdbcType?) {
        ps.setString(i, parameter.value)
    }

    @Throws(SQLException::class)
    override fun getNullableResult(rs: ResultSet, columnName: String): ExerciseStage? {
        val value = rs.getString(columnName)
        return mapStringToExerciseStage(value)
    }

    @Throws(SQLException::class)
    override fun getNullableResult(rs: ResultSet, columnIndex: Int): ExerciseStage? {
        val value = rs.getString(columnIndex)
        return mapStringToExerciseStage(value)
    }

    @Throws(SQLException::class)
    override fun getNullableResult(cs: CallableStatement, columnIndex: Int): ExerciseStage? {
        val value = cs.getString(columnIndex)
        return mapStringToExerciseStage(value)
    }

    /**
     * 将数据库字符串值映射到ExerciseStage枚举
     */
    private fun mapStringToExerciseStage(value: String?): ExerciseStage? {
        if (value == null) return null
        
        return when (value.lowercase()) {
            "reading" -> ExerciseStage.READING
            "listening" -> ExerciseStage.LISTENING
            "dialogue" -> ExerciseStage.DIALOGUE
            "expression" -> ExerciseStage.EXPRESSION
            // JSON结构下完成态由status表示；将旧值兼容映射到最终阶段
            "completed" -> ExerciseStage.EXPRESSION
            else -> {
                // 尝试按枚举名称匹配
                try {
                    ExerciseStage.valueOf(value.uppercase())
                } catch (e: IllegalArgumentException) {
                    // 默认为短文朗读
                    ExerciseStage.READING
                }
            }
        }
    }
}
